package com.zhouyibike.uu.ui.activity.hehuoren;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.AuthResult;
import com.zhouyibike.uu.entity.CheckPwdResult;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.LoginResult;
import com.zhouyibike.uu.entity.WithDrawIntroduceResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.mybike.MybikeActivity6;
import com.zhouyibike.uu.ui.activity.mywallet.TixianSuccessActivity;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.OrderInfoUtil2_0;
import com.zhouyibike.uu.utils.TextUtils;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class HehuorenTixiannewActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_wbd;
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private ImageView iv_icon;
    private TextView tv_miaoshu, tv_restmoney, tv_allmoney;
    private Button btn_submit;
    private String openid = "";
    private EditText et_txmoney;
    private LinearLayout ll_getid;
    private Dialog jubaodialog;
    private String dialog_title = "";
    private String danchemoney = "0", yiquanmoney = "0";
    private TextView danchemoneytv, yiquanmoneytv;
    private LinearLayout dancheshouruly, yiquanshouruly;
    private CheckBox danchecb, yiquancb;
    private int tixiantype = 0;
    private TextView typetv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tixianhehuoren);
        initView();
//        reloadAccountInfo();
        danchemoney=getIntent().getDoubleExtra("cantixianmoney",0)+"";
        tv_restmoney.setText(danchemoney);
        getMsgdialogxiaoxi();
        dancheshouruly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                danchecb.setChecked(true);
                yiquancb.setChecked(false);
                tixiantype = 0;
                typetv.setText("当前账号单车收入");
                tv_restmoney.setText(danchemoney);
            }
        });
        yiquanshouruly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                danchecb.setChecked(false);
                yiquancb.setChecked(true);
                tixiantype = 1;
                typetv.setText("当前账号翼券收入");
                tv_restmoney.setText(yiquanmoney);
            }
        });
    }

    private void getMsgdialogxiaoxi() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.CityWithDrawIntroduce(params),
                new ApiCallback<WithDrawIntroduceResult>() {

                    @Override
                    public void onSuccess(WithDrawIntroduceResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            dialog_title = model.getData().getIntroduce();
                            tv_miaoshu.setText(model.getData().getWithDrawTime());
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                        settixiannewDialog();
                    }
                });
    }

    private void initView() {
        typetv = (TextView) findViewById(R.id.typetv);
        danchecb = (CheckBox) findViewById(R.id.dancheshourubt);
        yiquancb = (CheckBox) findViewById(R.id.yiquanshourubt);
        dancheshouruly = (LinearLayout) findViewById(R.id.dancheshouruly);
        yiquanshouruly = (LinearLayout) findViewById(R.id.yiquanshouruly);
        danchemoneytv = (TextView) findViewById(R.id.danchemoneytv);
        yiquanmoneytv = (TextView) findViewById(R.id.yiquanmoneytv);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("提现申请");
        mBtnBack.setOnClickListener(this);
        iv_icon = (ImageView) findViewById(R.id.iv_tixian_icon);
        ll_wbd = (LinearLayout) findViewById(R.id.ll_tixian_wbd);
        tv_miaoshu = (TextView) findViewById(R.id.tv_tixian_miaoshu);
        tv_restmoney = (TextView) findViewById(R.id.tv_tixian_restmoney);
        tv_allmoney = (TextView) findViewById(R.id.tv_tixian_allmoney);
        tv_allmoney.setOnClickListener(this);
        btn_submit = (Button) findViewById(R.id.btn_tixian_submit);
        btn_submit.setOnClickListener(this);
        et_txmoney = (EditText) findViewById(R.id.et_tixian_txmoney_new);
        ll_getid = (LinearLayout) findViewById(R.id.ll_tixian_getopenid);
        ll_getid.setOnClickListener(this);
        try {
            openid=preferences.getString("zfbid","");
            if (TextUtils.isNullorEmpty(openid))
            {

            }else{
                ll_wbd.setVisibility(View.GONE);
                iv_icon.setImageResource(R.mipmap.zfb_bd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void reloadAccountInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.ReloadAccountInfo(params),
                new ApiCallback<LoginResult>() {

                    @Override
                    public void onSuccess(LoginResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("token", model.getData().getToken());
                            edit.putString("fullName", model.getData().getFullName());
                            edit.putString("headPicture", model.getData().getHeadPicture());
                            edit.putString("nickName", model.getData().getNickName());
                            edit.putString("status", model.getData().getStatus());
                            if (model.getData().getStatus().equals("11") || model.getData().getStatus().equals("3")) {
                                edit.putString("status", "3");
                            }
                            edit.putString("createTime", model.getData().getCreateTime());
                            edit.putBoolean("hasPassword", model.getData().isHasPassword());
                            edit.putString("lastLoginTime", model.getData().getLastLoginTime());
                            edit.putString("minAmountForRiding", model.getData().getMinAmountForRiding());
                            edit.putString("rechargeAmount", model.getData().getRechargeAmount());
                            edit.putString("incomeAmount", model.getData().getIncomeAmount());
                            edit.putString("totalAmount", model.getData().getTotalAmount());
                            edit.putString("yiQuanIncoming", model.getData().getYiQuanIncoming());
                            edit.commit();
                            // tv_restmoney.setText(model.getData().getIncomeAmount());
                            try {
                                yiquanmoney = model.getData().getYiQuanIncoming();
                                danchemoney = model.getData().getIncomeAmount();
                                DecimalFormat df = new DecimalFormat("######0.00");
                                df.setRoundingMode(RoundingMode.DOWN);//都舍
                                danchemoney = (df.format(Double.parseDouble(model.getData().getIncomeAmount())) + "");
                                yiquanmoney = (df.format(Double.parseDouble(model.getData().getYiQuanIncoming())) + "");
//                                tv_restmoney.setText(((int) (Double.parseDouble(model.getData().getIncomeAmount())) + ""));
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
//                                tv_restmoney.setText(((Double.parseDouble(model.getData().getIncomeAmount())) + ""));
                            }

//                            danchemoney="789";yiquanmoney="12.88";
                            yiquanmoneytv.setText(yiquanmoney);
                            danchemoneytv.setText(danchemoney);
                            tv_restmoney.setText(danchemoney);
                        }
//                        else if(model.getStatus()==600){
//                            SharedPreferences.Editor edit=preferences.edit();
//                            edit.clear();
//                            edit.commit();
//                            startActivity(new Intent(TixiannewActivity.this,MainActivity.class));
//                            finish();
//                        }else{
//                            SharedPreferences.Editor edit=preferences.edit();
//                            edit.clear();
//                            edit.commit();
//                            startActivity(new Intent(TixiannewActivity.this,MainActivity.class));
//                            finish();
//                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void tixian() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("alipayId", openid);
//        params.put("type", tixiantype + "");
        params.put("type","2");
        params.put("money", et_txmoney.getText().toString());
        showProgressDialog();
        addSubscription(apiStores.Withdraw(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent intent = new Intent(HehuorenTixiannewActivity.this, TixianSuccessActivity.class);
                            intent.putExtra("txmoney", et_txmoney.getText().toString());
                            startActivityForResult(intent, 400);
                            setResult(200);
                            finish();
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    /**
     * 支付密码设置dialog
     */
    private Dialog yzmdialog;

    private void initDailog() {
        View view = LayoutInflater.from(this).inflate(
                R.layout.tixian_dialog, null);
        yzmdialog = new Dialog(this, R.style.loading_dialog);
        final EditText et_name = (EditText) view.findViewById(R.id.et_yanzhengdialog_name);
        Button btn_sure = (Button) view.findViewById(R.id.btn_yanzhengdialog_sure);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isNullorEmpty(et_name.getText().toString())) {
                    toastShow("请输入完整信息");
                } else {
                    tixianyanzheng(et_name.getText().toString());
                }
            }
        });
        ImageView iv_dismis = (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yzmdialog.dismiss();
            }
        });
        yzmdialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        yzmdialog.setCancelable(true);
        yzmdialog.setCanceledOnTouchOutside(false);
        yzmdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.tv_tixian_allmoney:
                // et_txmoney.setText(preferences.getString("incomeAmount",""));
//                et_txmoney.setText((int) (Double.parseDouble(preferences.getString("incomeAmount","")))+"");
                if (tixiantype == 0)//单车
                {
                    et_txmoney.setText(danchemoney);
                } else if (tixiantype == 1)//翼券
                {
                    et_txmoney.setText(yiquanmoney);
                }
//                et_txmoney.setText((int) (Double.parseDouble(preferences.getString("incomeAmount", ""))) + "");
                break;
            case R.id.ll_tixian_getopenid:
                authV2();//支付宝openid
                break;
            case R.id.btn_tixian_submit:
                if (tixiantype == 0)//单车提现
                {
                    if (TextUtils.isNullorEmpty(openid)) {
                        toastShow("请先绑定支付宝账号");
                    } else if (TextUtils.isNullorEmpty(et_txmoney.getText().toString())) {
                        toastShow("请输入正确的提现金额");
                    } else {
                        initDailog();
                        yzmdialog.show();
                    }
                } else {
                    jubaodialog.show();
                }
                break;
        }
    }

    private static final int SDK_AUTH_FLAG = 2;

    public void authV2() {

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * authInfo的获取必须来自服务端；
         */
        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(Config.PID, Config.APPID, "zy", false);
        String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);

        String privateKey = Config.RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, false);
        final String authInfo = info + "&" + sign;
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(HehuorenTixiannewActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (resultStatus.equals("9000") && authResult.getResultCode().equals("200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        openid = authResult.getUserid();
                        SharedPreferences.Editor edit = preferences.edit();
                        edit.putString("zfbid",openid);
                        edit.commit();
                        ll_wbd.setVisibility(View.GONE);
                        iv_icon.setImageResource(R.mipmap.zfb_bd);
                    } else {
                        // 其他状态值则为授权失败
                        toastShow("获取支付宝账号信息失败，请重试");
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void tixianyanzheng(String pwd) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("pwd", pwd);
        showProgressDialog();
        addSubscription(apiStores.CheckPwd(params),
                new ApiCallback<CheckPwdResult>() {

                    @Override
                    public void onSuccess(CheckPwdResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            yzmdialog.dismiss();
                            tixian();
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void settextcolorwithstr(TextView view, String str, int color) {
        int fstart = view.getText().toString().indexOf(str);
        int fend = fstart + str.length();
        SpannableStringBuilder style = new SpannableStringBuilder(view.getText().toString());
        style.setSpan(new UnderlineSpan(), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        style.setSpan(new UnderlineSpan(), fstart + 5, fend + 5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        style.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                setResult(886);//关闭
                startActivity(new Intent(HehuorenTixiannewActivity.this, MybikeActivity6.class));
                finish();
            }
        }, fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        style.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                setResult(885);//关闭且打开兑换区
                finish();
            }
        }, fstart + 5, fend + 5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        style.setSpan(new ForegroundColorSpan(color), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        style.setSpan(new ForegroundColorSpan(color), fstart + 5, fend + 5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        view.setText(style);
    }

    public class NoUnderlineSpan extends UnderlineSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
        }
    }

    private void settextcolorwithstr2(TextView view, String str, int color) {
//        尊敬的用户，您本次交易金额的20%将用于翼券抢购，适用于《翼券服务协议》。
//        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE //前后都不包括
//        Spannable.SPAN_INCLUSIVE_EXCLUSIVE  //前包括后不包括
//        Spannable.SPAN_EXCLUSIVE_INCLUSIVE  //前不包括后包括
//        Spannable.SPAN_INCLUSIVE_INCLUSIVE  //前后都包括

        try {
            int fstart = str.indexOf("《");
            int fend = str.indexOf("》");
            SpannableStringBuilder style = new SpannableStringBuilder(str);
            style.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View view) {
//                    jubaodialog.dismiss();
                    getWZMsg();
                }
            }, fstart, fend+1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            style.setSpan(new ForegroundColorSpan(color), fstart, fend+1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            style.setSpan(new NoUnderlineSpan(), fstart, fend+1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            view.setText(style);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //提现对话框1
    private void settixiannewDialog() {
        TextView tixiandialogquxiao, tixiandialogqueding, notes, note2;
        LayoutInflater inflater = LayoutInflater.from(HehuorenTixiannewActivity.this);
        final View headview = inflater.inflate(R.layout.tixiantishi_dialog, null, false);
        tixiandialogquxiao = headview.findViewById(R.id.tixiandialogquxiao);
        tixiandialogqueding = headview.findViewById(R.id.tixiandialogqueding);
        notes = headview.findViewById(R.id.notes);
        note2 = headview.findViewById(R.id.note2);
        notes.setMovementMethod(LinkMovementMethod.getInstance());
        notes.setHighlightColor(getResources().getColor(android.R.color.transparent));
        note2.setMovementMethod(LinkMovementMethod.getInstance());
        note2.setHighlightColor(getResources().getColor(android.R.color.transparent));
        try {
//《翼券服务协议》
            settextcolorwithstr2(notes, dialog_title, getResources().getColor(R.color.radio_button_selected_color));
        } catch (Exception e) {
            e.printStackTrace();
            notes.setText(dialog_title);
        }
//        SpannableString spannableString = new SpannableString("您的翼券还可以购买单车、购买商品。");
        settextcolorwithstr(note2, "购买单车", getResources().getColor(R.color.edit_frame));
//        settextcolorwithstr(note2,"购买商品",getResources().getColor(R.color.zhexiantutvvalue));
        jubaodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        jubaodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        jubaodialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = jubaodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = (int) (DataSingle.getInstance().PhoneW * 0.75); // 宽度
//        lp.height = (int) (DataSingle.getInstance().PhoneW * 0.75);
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        tixiandialogquxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
            }
        });
        tixiandialogqueding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isNullorEmpty(openid)) {
                    toastShow("请先绑定支付宝账号");
                } else if (TextUtils.isNullorEmpty(et_txmoney.getText().toString())) {
                    toastShow("请输入正确的提现金额");
                } else {
                    initDailog();
                    yzmdialog.show();
                }
                jubaodialog.dismiss();
            }
        });
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        jubaodialog.setOnKeyListener(keylistener);
    }

    private void getWZMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", "7");
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(HehuorenTixiannewActivity.this, TotalWebActivity.class);
                            i.putExtra("title", "翼券服务协议");
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
}
